package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.question.domain.Ppt;
import com.wuwei.elearning.question.domain.Video;
import com.wuwei.elearning.question.domain.Word;
import com.wuwei.elearning.question.domain.Word;
import com.wuwei.elearning.question.mapper.WordMapper;
import com.wuwei.elearning.question.service.WordService;
import com.wuwei.elearning.service.CacheService;
import com.wuwei.elearning.utils.AudioUtil;
import com.wuwei.elearning.utils.FileUtils;
import com.wuwei.elearning.utils.MinioUtil;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import io.minio.GetObjectResponse;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2025-03-20
 */
@RestController
@RequestMapping("/elearning/word")
@CrossOrigin
public class WordController {

    @Resource
    private WordMapper wordMapper;

    /**
     * 显示所有音频信息的方法
     * @param params
     * @param request
     * @return
     */
    @GetMapping("getList")
    public Result<List<Word>> getList(@RequestParam Map<String, String> params, HttpServletRequest request){
        String fileName = params.get("fileName");
        Integer currentPage = Integer.parseInt(params.get("currentPage"));
        Integer pageSize = Integer.parseInt(params.get("pageSize"));
        LambdaQueryWrapper<Word> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!"".equals(fileName),Word::getName,fileName);

        IPage<Word> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(currentPage);

        IPage<Word> WordIPage = wordMapper.selectPage(page, wrapper);
        List<Word> records = WordIPage.getRecords();

        for (Word word : records) {
            String upload = word.getUrl();
            // 构建Redis键
            String redisKey = Constant.MINIO_PDF + upload;
            // 尝试从Redis获取
            String url = cacheService.getPdf(upload, redisKey);
            word.setUrl(url);
        }
        return Result.ok(records);
    }

    @Resource
    private CacheService cacheService;


    @GetMapping("getTotal")
    public Result<Long> getTotal(@RequestParam Map<String, String> params){
        String fileName = params.get("fileName");
        LambdaQueryWrapper<Word> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!"".equals(fileName),Word::getName,fileName);
        Long count = wordMapper.selectCount(queryWrapper);
        return Result.ok(count);
    }

    @SneakyThrows
    @PostMapping("upload")
    public Result<String> upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        if (file.getSize() != 0) {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            if (!"docx".equalsIgnoreCase(suffix)&&!"doc".equalsIgnoreCase(suffix)) {
                response.setStatus(500);
                return Result.fail("请选择doc或docx格式的文件");
            }

            if (file.getSize()!=0) {
                wordService.insert(file);
                return Result.ok("上传成功");
            }
            response.setStatus(500);
            return Result.fail("上传失败！");
        } else {
            response.setStatus(500);
            return Result.fail("您没有上传任何文件");
        }
    }

    @PostMapping("delete")
    public Result<String> deleteByURL(@RequestBody Word word) {
        wordService.delete(word);
        return Result.ok("删除成功！");
    }

    @GetMapping("getAll")
    public Result<List<Word>> getAll(){
        LambdaQueryWrapper<Word> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(Word::getUrl)
                .ne(Word::getUrl, "");  // 添加url不为空字符串的条件
        List<Word> list = wordService.list(wrapper);
        return Result.ok(list);
    }

    @Resource
    private MinioUtil minioUtil;

    @GetMapping("preview")
    public void preview( HttpServletResponse response,@RequestParam("fileName") String fileName){
        response.setContentType(MediaType.APPLICATION_PDF_VALUE);
        try {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "inline; filename=" + URLEncoder.encode(fileName.replace(".docx", ".pdf"), StandardCharsets.UTF_8.name()));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        // 将 Word 转换为 PDF 并直接写入响应
        try {
            minioUtil.convertWordToPdfAndWrite(fileName, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Resource
    private WordService wordService;

}

